#!/usr/bin/env python
# encoding=utf-8
#codeby     道长且阻
#email      ydhcui@suliu.net/QQ664284092
#website    http://www.suliu.net


import os
import signal

import redis
import tornado.ioloop
import tornado.web
from tornado.httpserver import HTTPServer
from tornado.options import define, options, parse_command_line

import handlers
import settings

class Application(tornado.web.Application):
    def __init__(self):
        tornado.web.Application.__init__(self,
            handlers = handlers.Route.routes(),
            **settings.SETTINGS)

def runserver():
    http_server = HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    loop = tornado.ioloop.IOLoop.instance()

    def shutdown():
        print('Server stopping ...')
        http_server.stop()
        print('IOLoop wil  be terminate in 1 seconds')
        deadline = time.time() + 1

        def terminate():
            now = time.time()
            if now < deadline and (loop._callbacks or loop._timeouts):
                loop.add_timeout(now + 1, terminate)
            else:
                loop.stop()
                print('Server shutdown')
        terminate()

    def sig_handler(sig, frame):
        print('Caught signal:%s', sig)
        loop.add_callback(shutdown)

    signal.signal(signal.SIGINT, sig_handler)
    signal.signal(signal.SIGTERM, sig_handler)

    print('Server running on http://0.0.0.0:%d'%(options.port))
    loop.start()

def main():
    App = HTTPServer(Application(), xheaders=True)
    App.listen(options.port)
    loop = tornado.ioloop.IOLoop.instance()
    loop.start()

if __name__ == '__main__':
    define('port', default=8315, type=int)
    parse_command_line()
    main()

